#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
#include <syslog.h>

int g_stop = 0;
int             socket_fd = -1;
char            *server_ip;
int             port = 0;
char            MSG[50];
char 		timechar[256]={0};
void sig_handle(int signum)
{
        if(SIGUSR1 == signum)
        {
                g_stop = 1;
        }
}
void print_usage(char *progname)
{
	printf("%s usage: \n",progname);
	printf("-i(--ipaddr):specify IP address.\n");
	printf("-p(--port):specify server port.\n");
	printf("-t(--time):specify  sleep time.\n");
	printf("-d(--daemon):\n");
	printf("-h(--help): print this help information\n");
}

int ds18b20_get_temperature(float *temp);
int conn_server(void);
char *get_date_time(char *datetime);

int main(int argc,char **argv)
{	float		temp;
	char		*datetime;
	int		sle_time = 0;
	time_t		timep;
	time		(&timep);
	char 		*id = "JMQ";
	int		daemon_run = 0;
	int		opt;
        struct option           opts[] = { 
                {"ipaddr",required_argument,NULL,'i'},
                {"port",required_argument,NULL,'p'},
		{"time",required_argument,NULL,'t'},
		{"daemon",no_argument,NULL,'d'},
		{"help",no_argument,NULL,'h'},
                {NULL,0,NULL,0}
        };  

        while((opt = getopt_long(argc,argv,"i:p:t:dh",opts,NULL)) != -1) 
        {   
                switch(opt)
                {   
                        case 'i':
                                server_ip = optarg;
                                break;
                        case 'p':
                                port = atoi(optarg);
                                break;
                        case 't':
                                sle_time = atoi(optarg);
				break;
			case 'd':
				daemon_run = 1;
				break;
			case 'h':
				print_usage(argv[0]);
				return 0;
					
	
                }   
        }
	if (!port || !server_ip)
	{
		print_usage(argv[0]);

		return 0;
	}
	if(daemon_run)
	{
		daemon(0,0);
	}
	signal(SIGUSR1,sig_handle);
	while(!g_stop)
	{
		if( ds18b20_get_temperature(&temp) < 0 )
		{
			syslog(LOG_INFO,"ERROR:ds18b20 get temperrature failure\n");
			return -1;
		}
		printf("get temp: %f摄氏度\n",temp);
		datetime = get_date_time(datetime);
		printf("DATE:%s\n",datetime);
		memset(MSG,0,sizeof(MSG));
		int ret = snprintf(MSG,50,"%s/%s/%f",id,datetime,temp);
		printf("ret:%d,%d\n",ret,sizeof(MSG));
		if (ret < 0)
		{
			printf("snprintf() failure:%s\n",strerror(errno));
		}
		printf("MSG: %s\n",MSG);

		if( conn_server() < 0 )
		{
			syslog(LOG_INFO,"ERROR:Connect to server failure\n");
			close(socket_fd);
			return -2;
		}
		syslog(LOG_NOTICE,"Send message success\n");
		sleep(sle_time);


	}
	
	return 0;	

}

char * get_date_time(char *datetime)
{
	struct tm	*timenow;
	time_t		second=time(0);
	timenow = localtime(&second);
	sprintf(timechar,"%d-%d-%d %d:%d:%d",timenow->tm_year+1900,timenow->tm_mon+1,\
	timenow->tm_mday,timenow->tm_hour,timenow->tm_min,timenow->tm_sec);
	datetime = timechar;
	return datetime;



}
int ds18b20_get_temperature(float *temp)
{
        char    w1_path[50] = "/sys/bus/w1/devices/";
        char    chip[20];
        char    buf[128];
        DIR     *dirp;
        struct dirent   *direntp;
        int     fd = -1; 
        char    *ptr;
        float   value;
        int     found = 0;


        if( !temp )
        {   
    
                return -1; 
        }    

        if(( dirp = opendir(w1_path)) == NULL)
        {   
                printf("Open dir error: %s\n",strerror(errno));
                return -2;
        }

        while((direntp = readdir(dirp)) != NULL)
        {
                if(strstr(direntp->d_name,"28-"))
                {
                        strcpy(chip,direntp->d_name);
                        found = 1;
                }
        }
        closedir(dirp);

        if( !found )
        {
                printf("Can not find ds18b20 in %S\n",w1_path);
                return -4;
        }

        strncat(w1_path,chip,sizeof(chip)-1);
        strcat(w1_path,"/w1_slave");

        if( (fd=open(w1_path,O_RDONLY))<0 )
        {
                printf("Open %s error: %s\n",w1_path,strerror(errno));
                return -4;
        }

        if( read(fd,buf,sizeof(buf))<0 )
        {
                printf("read %s error: %s\n",w1_path,strerror(errno));
                return -5;
        }

        ptr = strstr(buf,"t=")+2;

        if( !ptr )
        {
                printf("ERROR:Can not get temperature\n");
                return -6;
        }

        *temp = atof(ptr)/1000;
        return 0;
}
int conn_server(void)
{
	int			rv = -1;
	struct sockaddr_in	server_addr;
	socket_fd = socket(AF_INET,SOCK_STREAM,0);
        if(socket_fd < 0)
        {   
                printf("Create socket failure: %s\n",strerror(errno));
                return -1; 
        }   
        printf("Create socket[%d] successful!\n",socket_fd);
    
        memset(&server_addr,0,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(port);
        inet_aton(server_ip,&server_addr.sin_addr);

        rv = connect(socket_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
        if( rv < 0)
        {   
                printf("Connect to server[%s:%d] failure: %s\n",server_ip,port,strerror(errno));
                return -2; 
        }   
        printf("Connect to server[%s:%d] successful!\n",server_ip,port);
	
	 rv = write(socket_fd,MSG,strlen(MSG));
        if( rv < 0 )
        {
                printf("Write to server by socket_fd[%d] failure: %s\n",socket_fd,strerror(errno));
                return -3;
        }
        printf("Write to server by socket_fd[%d] successful!\n",socket_fd);
	close(socket_fd);
	
	return rv;
}
